package org.ihelpuoo.orm.handler.dom;

import java.lang.reflect.Field;

import org.ihelpuoo.lang.ObjectUtils;
import org.ihelpuoo.orm.FieldRule;
import org.ihelpuoo.orm.IIIException;
import org.ihelpuoo.orm.ObjectRule;
import org.ihelpuoo.orm.handler.ObjectProcessor;
import org.ihelpuoo.orm.handler.SaveNormalFieldHandler;
import org.w3c.dom.Comment;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

public class EleSaveNormalFieldHandler extends SaveNormalFieldHandler
{

	public EleSaveNormalFieldHandler(ObjectProcessor beanHandler)
	{
		super(beanHandler);
	}

	@Override
	protected void setValueToSourceObject(ObjectRule r, Field f, Object src, Object v)
			throws Exception
	{
		String nn = null;
		int nodeType = r.getDomNodeType(f);
		switch (nodeType)
		{
		case FieldRule.ATTRIBUTE_NODE:
			nn = r.getDomNodeName(f);
			((Element)src).setAttribute(nn,ObjectUtils.castObjectToCharSequence(v).toString());
			break;
		case FieldRule.ELEMENT_NODE:
			nn = r.getDomNodeName(f);
			Element ele = ((Node)src).getOwnerDocument().createElement(nn);
			ele.setTextContent(ObjectUtils.castObjectToCharSequence(v).toString());
			((Node)src).appendChild(ele);
			break;
		case FieldRule.TEXT_NODE:
			((Element)src).setTextContent(ObjectUtils.castObjectToCharSequence(v).toString());
			break;
		case FieldRule.COMMENT_NODE:
			Comment cmt = ((Node)src).getOwnerDocument().createComment(
					ObjectUtils.castObjectToCharSequence(v).toString());
			((Node)src).getParentNode().insertBefore(cmt,((Node)src));
			break;
		default:
			throw new IIIException("Unknow field type '" + nodeType + "' of field '" + f.getName()
					+ "' of class '" + r.getType().getName() + "'");
		}
	}
}
